import React, { useState, useRef } from 'react';
import { getColumnDisplayText } from '../utils/columnHelper';
import './InfoPanel.css';

// 货位信息面板
export default function InfoPanel({ selectedSlot, warehouseData, onClose, onUpdateSlot, mousePosition }) {
  const [isEditing, setIsEditing] = useState(false);
  
  // 使用ref来存储初始位置，确保面板位置在弹出后不会变化
  const panelPositionRef = useRef(null);
  
  // 计算面板位置，确保不会超出屏幕边界
  const calculatePosition = (position) => {
    const panelWidth = 300; // 面板宽度
    const panelHeight = 400; // 面板预估高度
    const offset = 15; // 鼠标与面板的间距
    
    let left = position.x + offset;
    let top = position.y + offset;
    
    // 确保面板不会超出右边界
    if (left + panelWidth > window.innerWidth) {
      left = position.x - panelWidth - offset;
    }
    
    // 确保面板不会超出左边界
    if (left < 0) {
      left = 0;
    }
    
    // 确保面板不会超出底部边界
    if (top + panelHeight > window.innerHeight) {
      top = position.y - panelHeight - offset;
    }
    
    // 确保面板不会超出顶部边界
    if (top < 0) {
      top = 0;
    }
    
    return { left, top };
  };
  
  // 只在第一次渲染时计算并存储位置
  if (panelPositionRef.current === null) {
    panelPositionRef.current = calculatePosition(mousePosition);
  }
  
  const position = panelPositionRef.current;
  const [editData, setEditData] = useState({
    hasGoods: false,
    goodsInfo: {
      name: '',
      quantity: 0,
      weight: '',
      entryDate: ''
    }
  });

  // 修复：正确检查selectedSlot是否存在
  if (!selectedSlot || !warehouseData.slots || !warehouseData.slots[selectedSlot]) {
    return null;
  }

  const slot = warehouseData.slots[selectedSlot];
  
  // 初始化编辑数据
  React.useEffect(() => {
    setEditData({
      hasGoods: slot.hasGoods || false,
      goodsInfo: slot.goodsInfo || {
        name: '',
        quantity: 0,
        weight: '',
        entryDate: new Date().toISOString().split('T')[0]
      }
    });
    setIsEditing(false);
  }, [selectedSlot, slot]);
  
  const rowNames = ['第1排', '第2排', '第3排', '第4排'];
  const rowSide = slot.row < 2 ? '左侧' : '右侧';
  const columnDisplayText = getColumnDisplayText(slot.column, warehouseData.columns);

  const handleSave = async () => {
    try {
      await onUpdateSlot(selectedSlot, editData.hasGoods, editData.hasGoods ? editData.goodsInfo : null);
      setIsEditing(false);
      alert('✅ 货位信息更新成功！');
    } catch (err) {
      alert('❌ 更新失败: ' + err.message);
    }
  };

  const handleCancel = () => {
    // 恢复原始数据
    setEditData({
      hasGoods: slot.hasGoods || false,
      goodsInfo: slot.goodsInfo || {
        name: '',
        quantity: 0,
        weight: '',
        entryDate: new Date().toISOString().split('T')[0]
      }
    });
    setIsEditing(false);
  };

  if (isEditing) {
    return (
      <div 
        className="info-panel" 
        style={{
          left: `${position.left}px`,
          top: `${position.top}px`
        }}
      >
        <div className="info-header">
          <h3>编辑货位信息</h3>
          <button className="close-btn" onClick={onClose}>✕</button>
        </div>
        
        <div className="info-content">
          <div className="info-item">
            <span className="label">货位编号:</span>
            <span className="value">{slot.id}</span>
          </div>
          
          <div className="info-item">
            <span className="label">货物状态:</span>
            <select 
              value={editData.hasGoods ? 'occupied' : 'empty'}
              onChange={(e) => setEditData({
                ...editData,
                hasGoods: e.target.value === 'occupied'
              })}
              className="status-select"
            >
              <option value="empty">空闲</option>
              <option value="occupied">有货</option>
              </select>
          </div>
          
          {editData.hasGoods && (
            <>
              <div className="divider"></div>
              <h4>货物信息</h4>
              
              <div className="info-item">
                <span className="label">货物名称:</span>
                <input
                  type="text"
                  value={editData.goodsInfo.name}
                  onChange={(e) => setEditData({
                    ...editData,
                    goodsInfo: {
                      ...editData.goodsInfo,
                      name: e.target.value
                    }
                  })}
                  className="edit-input"
                />
              </div>
              
              <div className="info-item">
                <span className="label">货物数量:</span>
                <input
                  type="number"
                  value={editData.goodsInfo.quantity}
                  onChange={(e) => setEditData({
                    ...editData,
                    goodsInfo: {
                      ...editData.goodsInfo,
                      quantity: parseInt(e.target.value) || 0
                    }
                  })}
                  className="edit-input"
                  min="0"
                />
              </div>
              
              <div className="info-item">
                <span className="label">货物重量:</span>
                <input
                  type="text"
                  value={editData.goodsInfo.weight}
                  onChange={(e) => setEditData({
                    ...editData,
                    goodsInfo: {
                      ...editData.goodsInfo,
                      weight: e.target.value
                    }
                  })}
                  className="edit-input"
                  placeholder="例如: 150.5 kg"
                />
              </div>
              
              <div className="info-item">
                <span className="label">入库日期:</span>
                <input
                  type="date"
                  value={editData.goodsInfo.entryDate}
                  onChange={(e) => setEditData({
                    ...editData,
                    goodsInfo: {
                      ...editData.goodsInfo,
                      entryDate: e.target.value
                    }
                  })}
                  className="edit-input"
                />
              </div>
            </>
          )}
          
          <div className="button-group">
            <button className="save-btn" onClick={handleSave}>保存</button>
            <button className="cancel-btn" onClick={handleCancel}>取消</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div 
      className="info-panel" 
      style={{
        left: `${position.left}px`,
        top: `${position.top}px`
      }}
    >
      <div className="info-header">
        <h3>货位信息</h3>
        <button className="close-btn" onClick={onClose}>✕</button>
      </div>
      
      <div className="info-content">
        <div className="info-item">
          <span className="label">编号:</span>
          <span className="value">{slot.id}</span>
        </div>
        
        <div className="info-item">
          <span className="label">排:</span>
          <span className="value">第{slot.row}排</span>
        </div>
        
        <div className="info-item">
          <span className="label">列:</span>
          <span className="value">{columnDisplayText}</span>
        </div>
        
        <div className="info-item">
          <span className="label">层:</span>
          <span className="value">第{slot.layer}层</span>
        </div>

        <div className="info-item">
          <span className="label">状态:</span>
          <span className={`status ${slot.hasGoods ? 'occupied' : 'empty'}`}>
            {slot.hasGoods ? '有货' : '空闲'}
          </span>
        </div>
        
        {slot.hasGoods && slot.goodsInfo && (
          <>
            <div className="divider"></div>
            <h4>货物信息</h4>
            
            <div className="info-item">
              <span className="label">名称:</span>
              <span className="value">{slot.goodsInfo.name}</span>
            </div>
            
            <div className="info-item">
              <span className="label">数量:</span>
              <span className="value">{slot.goodsInfo.quantity}</span>
            </div>
            
            <div className="info-item">
              <span className="label">重量:</span>
              <span className="value">{slot.goodsInfo.weight}</span>
            </div>
            
            <div className="info-item">
              <span className="label">入库日期:</span>
              <span className="value">{slot.goodsInfo.entryDate}</span>
            </div>
          </>
        )}
        
        <div className="button-group">
          <button className="save-btn" onClick={() => setIsEditing(true)}>编辑</button>
        </div>
      </div>
    </div>
  );
}